<template>
  <div class="wrapper">
    <!-- header部分 -->
    <header>
      <p>确认订单</p>
    </header>

    <div v-if="isLoading" class="loading">
      <p>正在加载订单信息...</p>
    </div>

    <div v-else>
      <!-- 订单信息部分 -->
      <div class="order-info">
        <h5>订单配送至：</h5>
        <div class="order-info-address" @click="toUserAddress">
          <p>{{ addressText }}</p>
          <i class="fa fa-angle-right"></i>
        </div>
        <p v-if="contactInfo">{{ contactInfo }}</p>
      </div>

      <h3>{{ businessName }}</h3>

      <!-- 订单明细部分 -->
      <ul class="order-detailed" v-if="cartItems.length > 0">
        <li v-for="item in cartItems" :key="item.cartId">
          <div class="order-detailed-left">
            <img :src="item.foodImg" @error="handleImageError" alt="商品图片" />
            <p>{{ item.foodName }} x {{ item.quantity }}</p>
          </div>
          <p>&#165;{{ item.totalPrice }}</p>
        </li>
      </ul>
      
      <div v-else class="no-items">
        <p>购物车为空</p>
      </div>
      
      <div class="order-deliveryfee">
        <p>配送费</p>
        <p>&#165;{{ deliveryPrice }}</p>
      </div>

      <!-- 合计部分 -->
      <div class="total">
        <div class="total-left">&#165;{{ finalTotal }}</div>
        <div class="total-right" @click="toPayment">去支付</div>
      </div>
    </div>
  </div>
</template>

<script setup>
import qs from "qs";
import { useRouter, useRoute } from "vue-router";
import { ref, computed, inject } from "vue";
import { getSessionStorage, getLocalStorage } from "../common.js";
// 导入默认商品图片
import defaultFoodImg from '@/assets/sp01.png';

const axios = inject("axios");
const router = useRouter();
const route = useRoute();

const user = getSessionStorage("user");
console.log('Orders页面用户数据:', user);
const deliveryaddress = user ? getLocalStorage(user.userId) : null;
console.log('Orders页面配送地址:', deliveryaddress);
const businessId = route.query.businessId;
console.log('Orders页面商家ID:', businessId);
const business = ref({});
const cartArr = ref([]);
const isLoading = ref(true);

// 安全的计算属性
const addressText = computed(() => {
  return deliveryaddress && deliveryaddress.address ? deliveryaddress.address : "请选择送货地址";
});

const contactInfo = computed(() => {
  if (!deliveryaddress || !deliveryaddress.contactName) return null;
  const sex = deliveryaddress.contactSex == 1 ? "先生" : "女士";
  return `${deliveryaddress.contactName}${sex} ${deliveryaddress.contactId || ''}`;
});

const businessName = computed(() => {
  return business.value && business.value.businessName ? business.value.businessName : "商家信息加载中...";
});

const deliveryPrice = computed(() => {
  return business.value && business.value.deliveryPrice ? business.value.deliveryPrice : 0;
});

const cartItems = computed(() => {
  if (!cartArr.value || !Array.isArray(cartArr.value)) return [];
  return cartArr.value.map(item => ({
    cartId: item.cartId || Math.random(),
    foodName: item.food && item.food.foodName ? item.food.foodName : '商品',
    foodImg: item.food && item.food.foodImg ? item.food.foodImg : defaultFoodImg,
    quantity: item.quantity || 0,
    totalPrice: item.food && item.food.foodPrice ? (item.food.foodPrice * item.quantity) : 0
  }));
});

const totalPrice = computed(() => {
  let total = 0;
  for (let item of cartItems.value) {
    total += item.totalPrice;
  }
  return total;
});

const finalTotal = computed(() => {
  return totalPrice.value + deliveryPrice.value;
});

const init = async () => {
  console.log('开始初始化Orders页面');
  
  if (!user || !user.userId) {
    console.error('用户未登录，无法加载订单数据');
    isLoading.value = false;
    return;
  }
  
  if (!businessId) {
    console.error('商家ID缺失，无法加载订单数据');
    isLoading.value = false;
    return;
  }
  
  try {
    console.log('开始发送API请求...');
    const [businessResponse, cartResponse] = await Promise.all([
      axios.post(
        "/api/BusinessController/getBusinessById",
        qs.stringify({
          businessId: businessId,
        })
      ),
      axios.post(
        "/api/CartController/listCart",
        qs.stringify({
          userId: user.userId,
          businessId: businessId,
        })
      )
    ]);
    
    console.log('商家响应数据:', businessResponse);
    console.log('购物车响应数据:', cartResponse);
    
    // 根据日志，数据直接在响应对象中，而不是在.data属性中
    business.value = businessResponse;
    cartArr.value = cartResponse;
    
    console.log('Orders页面数据加载完成:', { 
      business: business.value, 
      cartArr: cartArr.value,
      businessKeys: business.value ? Object.keys(business.value) : 'null',
      cartLength: cartArr.value ? cartArr.value.length : 'null'
    });
  } catch (error) {
    console.error('Orders页面数据加载失败:', error);
  } finally {
    isLoading.value = false;
  }
};
init();

const toUserAddress = () => {
  router.push({
    path: "/userAddress",
    query: { businessId: businessId },
  });
};

const toPayment = () => {
  if (deliveryaddress == null) {
    alert("请选择送货地址！");
    return;
  }
  
  console.log('创建订单参数:', {
    userId: user.userId,
    businessId: businessId,
    daId: deliveryaddress.daId,
    orderTotal: totalPrice.value
  });
  
  axios
    .post(
      "/api/OrdersController/createOrders",
      qs.stringify({
        userId: user.userId,
        businessId: businessId,
        daId: deliveryaddress.daId,
        // 注意：orderTotal参数实际上后端不需要，但保留以防万一
        orderTotal: totalPrice.value,
      })
    )
    .then((response) => {
      console.log('创建订单API响应:', response);
      let orderId = response; // 修复：直接使用response，因为axios拦截器已经返回了data
      if (orderId > 0) {
        alert("订单创建成功！");
        router.push({ path: "/payment", query: { orderId: orderId } });
      } else {
        alert("创建订单失败！");
      }
    })
    .catch((error) => {
      console.error('创建订单失败:', error);
      alert("创建订单失败，请稍后重试！");
    });
};

// 处理图片加载错误
const handleImageError = (event) => {
  console.log('Orders页面图片加载失败，使用默认图片');
  event.target.src = defaultFoodImg;
};
</script>

<style scoped>
/****************** 总容器 ******************/
.wrapper {
  width: 100%;
  height: 100%;
}

/****************** 加载状态 ******************/
.loading {
  width: 100%;
  margin-top: 12vw;
  padding: 10vw;
  text-align: center;
  color: #666;
  font-size: 4vw;
}

/****************** 空购物车 ******************/
.no-items {
  width: 100%;
  padding: 8vw;
  text-align: center;
  color: #999;
  font-size: 4vw;
}

/****************** header部分 ******************/
.wrapper header {
  width: 100%;
  height: 12vw;
  background-color: #0097ff;
  color: #fff;
  font-size: 4.8vw;

  position: fixed;
  left: 0;
  top: 0;
  z-index: 1000;

  display: flex;
  justify-content: center;
  align-items: center;
}

/****************** 订单信息部分 ******************/
.wrapper .order-info {
  /*注意这里，不设置高，靠内容撑开。因为地址有可能折行*/
  width: 100%;
  margin-top: 12vw;
  background-color: #0097ef;
  box-sizing: border-box;
  padding: 2vw;
  color: #fff;
}

.wrapper .order-info h5 {
  font-size: 3vw;
  font-weight: 300;
}

.wrapper .order-info .order-info-address {
  width: 100%;
  display: flex;
  justify-content: space-between;
  align-items: center;

  font-weight: 700;
  user-select: none;
  cursor: pointer;
  margin: 1vw 0;
}

.wrapper .order-info .order-info-address p {
  width: 90%;
  font-size: 5vw;
}

.wrapper .order-info .order-info-address i {
  font-size: 6vw;
}

.wrapper .order-info p {
  font-size: 3vw;
}

.wrapper h3 {
  box-sizing: border-box;
  padding: 3vw;
  font-size: 4vw;
  color: #666;
  border-bottom: solid 1px #ddd;
}

/****************** 订单明细部分 ******************/
.wrapper .order-detailed {
  width: 100%;
}

.wrapper .order-detailed li {
  width: 100%;
  height: 16vw;
  box-sizing: border-box;
  padding: 3vw;
  color: #666;

  display: flex;
  justify-content: space-between;
  align-items: center;
}

.wrapper .order-detailed li .order-detailed-left {
  display: flex;
  align-items: center;
}

.wrapper .order-detailed li .order-detailed-left img {
  width: 10vw;
  height: 10vw;
}

.wrapper .order-detailed li .order-detailed-left p {
  font-size: 3.5vw;
  margin-left: 3vw;
}

.wrapper .order-detailed li p {
  font-size: 3.5vw;
}

.wrapper .order-deliveryfee {
  width: 100%;
  height: 16vw;
  box-sizing: border-box;
  padding: 3vw;
  color: #666;
  display: flex;
  justify-content: space-between;
  align-items: center;
  font-size: 3.5vw;
}

/****************** 订单合计部分 ******************/
.wrapper .total {
  width: 100%;
  height: 14vw;

  position: fixed;
  left: 0;
  bottom: 0;

  display: flex;
}

.wrapper .total .total-left {
  flex: 2;
  background-color: #505051;
  color: #fff;
  font-size: 4.5vw;
  font-weight: 700;
  user-select: none;

  display: flex;
  justify-content: center;
  align-items: center;
}

.wrapper .total .total-right {
  flex: 1;
  background-color: #38ca73;
  color: #fff;
  font-size: 4.5vw;
  font-weight: 700;
  user-select: none;
  cursor: pointer;

  display: flex;
  justify-content: center;
  align-items: center;
}
</style>
